package com.zkyc.framework.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * o 给视频加水印
 *
 * @author admin
 */
public class FFMPEG {

    public static String LINUX_PATH = "/opt/ffmpeg/bin/ffmpeg";

    public static String WINDOWS_PATH = "D:\\download\\ffmpeg\\bin\\ffmpeg.exe";

    public static String dealString(String str) {
        Matcher m = java.util.regex.Pattern.compile("^frame=.*").matcher(str);
        String msg = "";
        while (m.find()) {
            msg = m.group();
        }
        return msg;
    }

    /**
     * 如果是数字就是成功的时间(秒数)
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 如果返回不是null的值就是成功(值为转换用时单位:秒)
     *
     * @param instr
     * @return
     */
    public static String returnSecond(String instr) {
        String returnValue = null;
        if (null != instr) {
            String[] a = instr.split("\\.");
            String[] b = a[0].split(":");
            int returnNumber = 0;
            if (null != instr && b[0].length() != 0) {
                returnNumber = Integer.valueOf(b[0]) * 60 * 60 + Integer.valueOf(b[1]) * 60 + Integer.valueOf(b[2]);
                returnValue = String.valueOf(returnNumber);
            } else {
                returnValue = null;
            }
        }
        return returnValue;
    }

    private static String getLocation(int location) {
        switch (location) {
            case 1:
                return "10:10"; //左上
            case 2:
                return "main_w-overlay_w-10:10"; //右上
            case 3:
                return "10:main_h-overlay_h-10"; //左下
            case 4:
                return "main_w-overlay_w-10:main_h-overlay_h-10";//右下
            default:
                return "main_w-overlay_w-10:10";
        }
    }

    /**
     * 获取视频格式(转码前的格式和转码后的格式都可以调用)
     *
     * @param outputPath
     * @return
     */
    public static String returnVideoFormat(String outputPath) {
        return outputPath.substring(outputPath.lastIndexOf(".") + 1);
    }
    /**
     * 截取视频图片
     * @param videoPath
     * @return
     */
    public static void videoCatchImg(String videoPath,String savePath) {
        File file = new File(videoPath);
        if (!file.exists()) {
            System.err.println("路径[" + videoPath + "]对应的视频文件不存在!");
            return ;
        }
        List<String> commands = new java.util.ArrayList<String>();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            commands.add(WINDOWS_PATH);
        } else {
            commands.add(LINUX_PATH);
        }
        //输入文件
        commands.add("-i");
        commands.add(videoPath);
        //输出文件若存在可以覆盖
        commands.add("-y");
        //指定图片编码格式
        commands.add("-f");
        commands.add("image2");
        //设置截取视频第3秒时的画面
        commands.add("-ss");
        commands.add("3");
        //截取的图片路径
        commands.add(savePath);
        System.out.println("commands:"+commands);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commands);
            builder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @ HashMap<String,String> dto 参数传递对象<br>
     * dto中包含的参数<br>
     * (必填)1.ffmpeg_path:ffmpeg执行文件地址,如 d:\\ffmpeg\\ffmpeg.exe
     * Linux下直接调用ffmpeg命令(当然你事先已经有这个程序了)<br>
     * (必填)2.input_path:原视频路径<br>
     * (必填)3.video_converted_path:转换后视频输出路径<br>
     * (可选)4.screen_size:视频尺寸 长度乘宽度 乘号用英文小写"x"如 512x480<br>
     * (可选)5.logo:水印地址(其实在ffmpeg中有一个专门的watermark参数,logo跟它有何不同,我还没看,不过对我来说效果一样
     * 貌似需要png图片才行)<br>
     * (可选,如果填写必须有logo才行,默认为0)6.xaxis:水印logo的横坐标(只有logo参数为一个正确路径才行) 比如0<br>
     * (可选,如果填写必须有logo才行,默认为0)6.yaxis:水印logo的纵坐标(只有logo参数为一个正确路径才行) 比如0<br>
     * (可选)vb:视频比特率,传入一个数值,单位在程序里面拼接了k (可选)ab:音频比特率,传入一个数值,单位在程序里面拼接了k
     */
    public String videoTransfer(HashMap<String, String> dto) {
        // String ffmpeg_path,String input_path,String video_converted_path,String
        // logo,String screen_size,String xaxis,String yaxis,String vb,String ab
        List<String> cmd = new ArrayList<String>();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            cmd.add(WINDOWS_PATH);
        } else {
            cmd.add(LINUX_PATH);
        }
        cmd.add("-y");
        cmd.add("-i");
        cmd.add(dto.get("input_path"));
        if (null != dto.get("screen_size")) {
            cmd.add("-s");
            cmd.add(dto.get("screen_size"));
        }
        if (null != dto.get("logo")) {
            String logo = dto.get("logo");
            cmd.add("-vf");
            String xaxis = dto.get("xaxis");
            String yaxis = dto.get("yaxis");
            xaxis = xaxis != null && !xaxis.equals("") ? xaxis : "0";
            yaxis = yaxis != null && !yaxis.equals("") ? yaxis : "0";
            xaxis = "main_w-overlay_w-10:main_h-overlay_h-10";
            //String logoString = "movie=" + logo + "[logo],[in][logo]overlay=x=" + xaxis + ":y=" + yaxis + "[out]";
            String logoString = "movie=" + logo + "[logo],[in][logo]overlay=x=" + xaxis + "[out]";
            cmd.add(logoString);
        }
        cmd.add("-strict");
        cmd.add("-2");
        if (null != dto.get("vb") && !dto.get("vb").equals("")) {
            cmd.add("-vb");
            cmd.add(dto.get("vb") + "k");
        }
        if (null != dto.get("ab") && !dto.get("ab").equals("")) {
            cmd.add("-ab");
            cmd.add(dto.get("ab") + "k");
        }
        cmd.add("-q:v");
        cmd.add("4");
        cmd.add(dto.get("video_converted_path"));
        String converted_time = CmdExecuter.exec(cmd);
        return returnSecond(converted_time);// 获取转换时间

    }

    public static void main(String[] arg) {
        HashMap<String, String> dto = new HashMap<String, String>();
        dto.put("ffmpeg_path",
                "D:\\download\\ffmpeg\\bin\\ffmpeg.exe");// 必填
        dto.put("input_path", "http://10.101.116.7:9000/zj-lab/3c6facdf3c655ea448b1c4b3e0c6910c.mp4");// 必填
        //dto.put("input_path", "http://10.101.116.7:9000/zj-lab/02249679-dc14-4f0b-8ab2-2dc810d67e5b.jpeg");// 必填
        dto.put("video_converted_path", "D:\\image\\video\\haha.mp4");// 必填
        dto.put("logo", "D\\\\:/Document/zjlab.png");// 可选(注意windows下面的logo地址前面要写4个反斜杠,如果用浏览器里面调用servlet并传参只用两个,如
        // d:\\:/ffmpeg/input/logo.png)
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor("http://10.101.116.7:9000/zj-lab/02249679-dc14-4f0b-8ab2-2dc810d67e5b.jpeg");
        System.out.println(type);
        String secondsString = new FFMPEG().videoTransfer(dto);
        System.out.println("转换共用:" + secondsString + "秒");
    }

    /**
     * @Description:下载
     * @Param downloadPath 文件路径
     */
    public static String downloadPathFile(String path, HttpServletRequest request, HttpServletResponse response) {
        //设置文件路径
        File file = new File(path);
        //获取文件名称
        String fileName = file.getName();
        //判断文件是否存在
        //if (file.exists()) {
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            file.delete();
            return "下载成功";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //}
        return "下载失败";
    }


}

